import { Controller, Inject, Get, Post, Body, Query } from '@midwayjs/core'
import { RescueInfoService } from '../../service/admin/RescueInfoService'
import { BaseController } from '../base.chontroller'

@Controller('/rescue_info')
export class RescueInfoController extends BaseController {
  @Inject()
  service!: RescueInfoService

  @Get('/list')
  async list(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('name') name?: string,
    @Query('childName') childName?: string
  ) {
    try {
      const pageNum = page ? parseInt(page) : 1
      const pageSizeNum = pageSize ? parseInt(pageSize) : 10
      const filters = {
        name: name || undefined,
        childName: childName || undefined
      }
      const data = await this.service.list(pageNum, pageSizeNum, filters)
      return this.success<IList<any>>(data)
    } catch (err: any) {
      return this.fail(err.message || '获取列表失败')
    }
  }

  @Get('/detail')
  async detail(@Query('id') id?: string) {
    if (!id) {
      return this.fail('缺少ID参数')
    }
    try {
      const data = await this.service.getById(parseInt(id))
      if (!data) {
        return this.fail('救助信息不存在')
      }
      return this.success(data)
    } catch (err: any) {
      return this.fail(err.message || '获取详情失败')
    }
  }

  @Post('/add')
  async add(@Body() data: any) {
    if (!data?.name) {
      return this.fail('缺少必要参数：救助名称')
    }
    try {
      const result = await this.service.add(data)
      return this.success(result, '添加成功')
    } catch (err: any) {
      return this.fail(err.message || '添加失败')
    }
  }

  @Post('/edit')
  async edit(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      const result = await this.service.edit(data)
      return this.success(result, '编辑成功')
    } catch (err: any) {
      return this.fail(err.message || '编辑失败')
    }
  }

  @Post('/delete')
  async delete(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      await this.service.delete(data.id)
      return this.success(null, '删除成功')
    } catch (err: any) {
      return this.fail(err.message || '删除失败')
    }
  }
}
